#!/usr/bin/env python
"""
开发环境启动脚本
"""
import os
import sys
import subprocess
import time
import signal
from pathlib import Path

# 添加项目路径到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

# 设置Django设置模块
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'devops_backend.settings')

def run_command(command, cwd=None, background=False):
    """运行命令"""
    print(f"执行命令: {command}")
    if background:
        return subprocess.Popen(command, shell=True, cwd=cwd)
    else:
        result = subprocess.run(command, shell=True, cwd=cwd)
        return result.returncode == 0

def check_dependencies():
    """检查依赖"""
    print("检查依赖...")
    
    # 检查Redis
    try:
        import redis
        r = redis.Redis(host='localhost', port=6379, db=0)
        r.ping()
        print("✓ Redis连接正常")
    except Exception as e:
        print(f"✗ Redis连接失败: {e}")
        print("请确保Redis服务正在运行")
        return False
    
    # 检查数据库
    try:
        import django
        django.setup()
        from django.db import connection
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
        print("✓ 数据库连接正常")
    except Exception as e:
        print(f"✗ 数据库连接失败: {e}")
        return False
    
    return True

def create_sample_data():
    """创建示例数据"""
    print("创建示例数据...")
    
    try:
        import django
        django.setup()
        
        from cmdb.models import Environment, HostType, Host
        from django.contrib.auth import get_user_model
        
        User = get_user_model()
        
        # 创建环境
        env_prod, _ = Environment.objects.get_or_create(
            code='prod',
            defaults={'name': '生产环境', 'description': '生产环境'}
        )
        
        env_test, _ = Environment.objects.get_or_create(
            code='test',
            defaults={'name': '测试环境', 'description': '测试环境'}
        )
        
        # 创建主机类型
        host_type_web, _ = HostType.objects.get_or_create(
            code='web',
            defaults={'name': 'Web服务器', 'description': 'Web服务器'}
        )
        
        host_type_db, _ = HostType.objects.get_or_create(
            code='db',
            defaults={'name': '数据库服务器', 'description': '数据库服务器'}
        )
        
        # 创建示例主机
        host1, created = Host.objects.get_or_create(
            hostname='web-server-01',
            defaults={
                'ip': '192.168.1.100',
                'environment': env_prod,
                'host_type': host_type_web,
                'ssh_port': 22,
                'ssh_username': 'root',
                'description': '生产环境Web服务器',
                'status': 'online'
            }
        )
        
        host2, created = Host.objects.get_or_create(
            hostname='db-server-01',
            defaults={
                'ip': '192.168.1.101',
                'environment': env_prod,
                'host_type': host_type_db,
                'ssh_port': 22,
                'ssh_username': 'root',
                'description': '生产环境数据库服务器',
                'status': 'online'
            }
        )
        
        print("✓ 示例数据创建完成")
        
    except Exception as e:
        print(f"✗ 创建示例数据失败: {e}")

def start_services():
    """启动服务"""
    print("启动开发服务...")
    
    processes = []
    
    try:
        # 启动Django开发服务器
        print("启动Django开发服务器...")
        django_process = run_command(
            "python manage.py runserver 0.0.0.0:8000",
            background=True
        )
        processes.append(('Django', django_process))
        
        # 启动Celery Worker
        print("启动Celery Worker...")
        celery_process = run_command(
            "celery -A devops_backend worker --loglevel=info",
            background=True
        )
        processes.append(('Celery Worker', celery_process))
        
        # 启动Celery Beat
        print("启动Celery Beat...")
        beat_process = run_command(
            "celery -A devops_backend beat --loglevel=info",
            background=True
        )
        processes.append(('Celery Beat', beat_process))
        
        print("\n" + "="*50)
        print("开发环境启动完成!")
        print("="*50)
        print("Django服务: http://localhost:8000")
        print("API文档: http://localhost:8000/api/docs/")
        print("管理后台: http://localhost:8000/admin/")
        print("健康检查: http://localhost:8000/health/")
        print("="*50)
        print("按 Ctrl+C 停止所有服务")
        print("="*50)
        
        # 等待中断信号
        def signal_handler(sig, frame):
            print("\n正在停止服务...")
            for name, process in processes:
                print(f"停止 {name}...")
                process.terminate()
                try:
                    process.wait(timeout=5)
                except subprocess.TimeoutExpired:
                    process.kill()
            print("所有服务已停止")
            sys.exit(0)
        
        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)
        
        # 保持运行
        while True:
            time.sleep(1)
            # 检查进程是否还在运行
            for name, process in processes:
                if process.poll() is not None:
                    print(f"警告: {name} 进程已退出")
    
    except KeyboardInterrupt:
        print("\n正在停止服务...")
        for name, process in processes:
            print(f"停止 {name}...")
            process.terminate()
        print("所有服务已停止")

def main():
    """主函数"""
    print("DevOps平台开发环境启动器")
    print("="*50)
    
    # 检查依赖
    if not check_dependencies():
        print("依赖检查失败，请解决问题后重试")
        sys.exit(1)
    
    # 运行迁移
    print("运行数据库迁移...")
    if not run_command("python manage.py migrate"):
        print("数据库迁移失败")
        sys.exit(1)
    
    # 创建示例数据
    create_sample_data()
    
    # 启动服务
    start_services()

if __name__ == '__main__':
    main()
